package io.renren.modules.oa.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.oa.dao.DeptDao;
import io.renren.modules.oa.entity.DeptEntity;
import io.renren.modules.oa.service.DeptService;


@Service("deptService")
public class DeptServiceImpl extends ServiceImpl<DeptDao, DeptEntity> implements DeptService {

    @Autowired
    private DeptDao deptDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DeptEntity> page = this.page(
                new Query<DeptEntity>().getPage(params),
                new QueryWrapper<DeptEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<DeptEntity> queryByCondition(String deptName) {
        List<DeptEntity> deptList = deptDao.queryByCondition(deptName);
        // 条件查询，要将子部门也带出来
        if (StringUtils.isNotBlank(deptName)) {
            deptList = getDeptTreeList(deptList);
        }

        for(DeptEntity deptEntity : deptList){
            DeptEntity parentDeptEntity = this.getById(deptEntity.getParentId());
            if(parentDeptEntity != null){
                deptEntity.setParentName(parentDeptEntity.getDeptName());
            }
        }

        return deptList;
    }

    /**
     * 递归查询子部门
     */
    private List<DeptEntity> getDeptTreeList (List<DeptEntity> deptList) {
        List<DeptEntity> allDeptList = new ArrayList<DeptEntity>();
        allDeptList.addAll(deptList);
        for (DeptEntity parentDept : deptList)  {
            List<DeptEntity> subDeptList = this.getByParentId(parentDept.getDeptId());
            if (subDeptList != null && subDeptList.size() > 0) {
                List<DeptEntity> allSubDeptList = getDeptTreeList(subDeptList);
                for (DeptEntity subDept : allSubDeptList) {
                    if (!allDeptList.contains(subDept)) allDeptList.add(subDept);
                }
            }
        }
        return allDeptList;
    }

    @Override
    public List<DeptEntity> getByParentId(Long parentId) {
        List<DeptEntity> list = deptDao.getByParentId(parentId);
        if (list != null && list.size() > 0) {
            return list;
        }
        return null;
    }

}